import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { generateIndexRouter } from '@/utils/util'

NProgress.configure({ showSpinner: false })
function getTokenByUrl () {
  const reg = new RegExp('(^|&)token=([^&]*)(&|$)') // 参数正则
  const codeUrl = window.location.hash.split('?')[1]
  let r = null
  if (codeUrl) {
    let params = null
    // 如果地址拼接token，先判断token是否符合规则，然后直接返回token进入系统
    if (codeUrl.includes('token')) {
      r = window.location.hash.split('?')[1].match(reg) // 匹配目标参数 匹配token
      if (r != null) {
        params = r[2]
      }
    }
    return params
  }
}
const whiteList = ['/user/login', '/register', '/registerPage', '/qrCode', '/qrVisitor']

router.beforeEach((to, from, next) => {
  NProgress.start()
  const urlToken = getTokenByUrl()
  if (urlToken && urlToken !== Vue.ls.get(ACCESS_TOKEN)) {
    Vue.ls.set(ACCESS_TOKEN, urlToken, 24 * 60 * 60 * 1000 * 50)
    window.location.reload()
    return
  }
  if (Vue.ls.get(ACCESS_TOKEN)) {
    if (to.path === '/user/login') {
      next('/')
      NProgress.done()
    } else {
      if (store.getters.permissionList.length === 0) {
        store
          .dispatch('GetPermissionList')
          .then(res2 => {
            let menuData = res2

            if (menuData === null || menuData === '' || menuData === undefined) {
              return
            }

            let constRoutes = generateIndexRouter(menuData)
            router.addRoutes(constRoutes)

            next({ path: to.fullPath })
          })
          .catch(() => {
            NProgress.done()
          })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next({ path: '/user/login' })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
